<?php
//пароль
if(!defined('INCONFIG')){header("Location: ../index.php"); die();}
includeLang('functions');

#Lang functions
/**
 * is_lang()
 * 
 * @param mixed $lang
 * @return
 */
function is_lang($lang)
{
	return file_exists('lang/'.$lang.'/functions.php')&&file_exists('lang/'.$lang.'/'.$lang.'.png');
}
/**
 * get_langs()
 * 
 * @return
 */
function get_langs()
{
	$handle = opendir('lang');
	$langlist = array();
	while ($file = readdir($handle)) {
		if (is_lang($file) && $file != '.' && $file != '..') {
			$langlist[] = $file;
		}
	}
	closedir($handle);
	sort($langlist);
	return $langlist;
}
/**
 * lang_selector()
 * 
 * @param string $sel_lang
 * @param bool $images
 * @return
 */
function lang_selector($sel_lang = '', $images = false)
{
	$langs = get_langs();
    if($images)
    {
        $cnt='';
        foreach($langs as $lang)
        {
            $border=$sel_lang==$lang?'1':'0';
            $cnt.='<a href="?p=chnglng&amp;lang='.$lang.'"><img src="img/'.$lang.'.png" title="'.$lang.'" alt="'.$lang.'" border="'.$border.'" width="32" height="32" /></a>';
        }
    }
    else
    {
    	$cnt = '<select name="lang" onchange="window.location=\'?p=chnglng&amp;lang=\'+this.options[this.selectedIndex].value">';
    	foreach ($langs as $lang)
        {
    		$cnt .= '<option value="'.$lang.'"'.($lang == $sel_lang ? ' selected="selected"' : '').'>'.$lang.'</option>';
        }
    	$cnt .= '</select>';
    }
	return $cnt;
}
/**
 * select_lang()
 * 
 * @return
 */
function select_lang()
{
    global $user;
	if ($user->logged() && $user->getVar('lang')!=null)
		$lang= $user->getVar('lang');
	elseif(isset($_COOKIE['lang']))
        $lang = $_COOKIE['lang'];
    else
		$lang = getConfig('settings','dlang', 'en');
	if (!is_lang($lang))
		$lang = getConfig('settings','dlang', 'en');
	return $lang;
}

/**
 * includeLang()
 * 
 * @param mixed $file
 * @return
 */
function includeLang($file)
{
	global $langpath, $Lang;
	$langpath=select_Lang();
	if(file_exists('lang/'.$langpath.'/'.$file.'.php'))
	{
	   	define('INLANG', True);
        require_once("lang/{$langpath}/{$file}.php");	
	}
}
#Message functions
/**
 * msg()
 * 
 * @param string $heading
 * @param string $text
 * @param string $div
 * @param integer $return
 * @return
 */
function msg($heading = '', $text = '', $div = 'success', $return=0) {
    $content='';
    $content .= '<table width="90%" border="0"><tr><td>';
    $content .= '<div align="center" class="'.$div.'">'.($heading ? '<b>'.$heading.'</b><br />' : '').$text.'</div></td></tr></table>';
    if($return) return $content; else echo $content;
}
/**
 * err()
 * 
 * @param mixed $head
 * @param mixed $text
 * @return
 */
function err($head, $text)
{
    head($head,0);
    msg($head,$text,'error');
    foot(0);
    exit();
}
/**
 * suc()
 * 
 * @param mixed $head
 * @param mixed $text
 * @return
 */
function suc($head, $text)
{
    head($head);
    msg($head,$text);
    foot();
    exit();
}
#Page selector
/**
 * pagechoose()
 * 
 * @param mixed $page
 * @param integer $count
 * @param mixed $page2
 * @return
 */
function pagechoose($page, $count=0, $page2)
{
    global $Lang;
    $top=getConfig('settings', 'items_per_page', '100');
    $content=NULL;
    $content.='<div class="page-choose" align="center"><table align="center"><tr>';
    
    $totalpages = ceil($count/$top);
    if($totalpages==0)
    {
        $totalpages++;
    }
    if($page>3)
    {
        $content.="<td><a href=\"index.php?p=$page2&amp;pg=1\" title=\"{$Lang['first']}\"  class=\"btn\"> &laquo; </a></td>";
    }
    if($page>1)
    {
        $content.="<td><a href=\"index.php?p=$page2&amp;pg=";
        $pg=$page-1;
        $content.=$pg;
        $content.="\" title=\"{$Lang['prev']}\" class=\"btn\"> &lt; </a></td>";
    }
    if($page-2>0){$start=$page-2;}else{$start=1;}
    for($i=$start; $i<=$totalpages && $i<=$page+2; $i++)
    {

        if($i==$page)
        {
            $content.= '<td>&nbsp;&nbsp;<a href="#" class="btn brown" title="';
            $content.= ' [';
            $content.= ($count!=0) ? $i*$top+1-$top : 0;
            $content.= ' - ';
            $content.= ($i*$top>$count)? $count: $i*$top;
            $content.= ']"> ';
            $content.= $i;
            $content.= ' </a>&nbsp;&nbsp;</td>';
        }
        else
        {
            $content.= '<td>&nbsp;&nbsp;<a href="index.php?p='.$page2;
            $content.= '&amp;pg='.$i;
            $content.= '" title="[';
            $content.= ($count!=0) ? $i*$top+1-$top : 0;
            $content.= ' - ';
            $content.= ($i*$top>$count)? $count: $i*$top;
            $content.= ']" class="btn"> ';
            $content.= $i;
            $content.= ' </a>&nbsp;&nbsp;</td>';
        }

    }
    if($totalpages > $page)
    {
        $content.="<td><a href=\"index.php?p=$page2&amp;pg=";
        $content.= $page+1;
        $content.="\" title=\"{$Lang['next']}\" class=\"btn\"> &gt; </a></td>";
    }
    if($totalpages > $page+2)
    {
        $content.="<td><a href=\"index.php?p=$page2&amp;pg=";
        $content.= $totalpages;
        $content.="\" title=\"{$Lang['last']}\" class=\"btn\"> &raquo; </a></td>";
    }

    $content.='</tr></table>&nbsp;</div>';
    return $content;

}
#Filter functions
/**
 * val_int()
 * 
 * @param mixed $string
 * @param integer $default
 * @param integer $min
 * @param integer $max
 * @return vaidated integer
 */
function val_int($string, $default=0, $min=0, $max=999999999)
{
    $options = array(
    'options' => array(
        'default' => $default,
        'min_range' => $min,
        'max_range' => $max),
    );
    $int = filter_var($string, FILTER_VALIDATE_INT, $options);
    return $int;
}
/**
 * val_string()
 * 
 * @param mixed $string
 * @return
 */
if(!function_exists('val_string'))
{
function val_string($string)
{
    global $sql;
    if(!is_array($string))
        $string = trim(htmlentities(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $sql->escape($string)), ENT_QUOTES, 'UTF-8'));
    else
    {
        $strings = array();
        foreach($string as $key => $value)
        {
            array_push($strings,val_string($value));
        }
        $string=$strings;
    }
    return $string;
}
}
/**
 * getVar()
 * 
 * @param $_REQUEST[$v] or $_POST[$v]
 * @param string, bool or int $t, default=string
 * @param null - return null if failed to validate
 * @return clean string, int, bool, float or null
 */
function getVar($v, $t='string', $null=false)
{
    $var=isset($_REQUEST[$v])?$_REQUEST[$v]:$_POST[$v];
    if($t=='int')
    {
        if(!is_numeric($var) && !$null) throw new Exception('Var: '.$v.' with value "'.$var.'" is not a number!');
        if(is_null($var) && $null) return null;
        return val_int($var);
    }
    else if($t=='bool')
        if($var=='')
            return '0';
        else
            return filter_var($var, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
    else if($t=='string')
        return val_string($var);
    else if($t=='float')
    {
        if(!is_numeric($var) && !$null) throw new Exception('Var: '.$v.' with value "'.$var.'" is not a number!');
        if(is_null($var) && $null) return null;
        if(isFloat($var))
            return 0.00+(float)$var;
        else if(is_int(0+$var))
            return getVar($v,'int',$null);
        else
            throw new Exception('Var: '.$v.' with value: '.$var.' failed to validate as float and int');
    }
    else if($t=='date')
    {
        $date_format=getConfig('settings','date_format','d.m.Y');
        return isDate($var);
    }
    else if($t=='time')
    {
        $timeparts=explode(':',$var,3);
        if($timeparts[2]!=null || !is_numeric($timeparts[0]) || !is_numeric($timeparts[1]))
            throw new Exception('Time: '.$var.' is not valid');
        return $timeparts[0].':'.$timeparts[1];
    }
    else if($t=='datetime')
    {
        throw new Exception('DateTime not implemented!');
    }
    else
        throw new Exception('Undefined type: '.$t.', var: '.$v.', value: '.$var);
}
#Config functions
/**
 * getConfig()
 * 
 * @param mixed $type
 * @param mixed $name
 * @param string $default
 * @return
 */
function getConfig($type, $name, $default='')
{
    global $CONFIG, $sql, $q;
    if(isset($CONFIG[$type][$name]))
    {
        return $CONFIG[$type][$name];
    }
    else
    {
        if($default!='')
        {
            setConfig($type,$name,$default);
            return $default;
        }
        return null;
    }
}
/**
 * setConfig()
 * 
 * @param mixed $type
 * @param mixed $name
 * @param mixed $val
 * @return
 */
function setConfig($type, $name, $val)
{
    global $CONFIG, $sql, $q;
    $CONFIG[$type][$name]=$val;
    $qry=$sql->query(672, array('type_id'=>$type));
    if($sql->num_rows($qry))
    {
        $type=$sql->fetch_array($qry);
        $id=$type['id'];
    }
    else
    {
        $sql->query(673, array('type'=>$type));
        $id=$sql->getId();
    }
    
    $params = array('name'=>$name, 'type'=> $id, 'val'=>$val);
    $qry=$sql->query(671, $params);
    if($sql->num_rows($qry)>0)
    {
        $sql->query(670, $params);
    }
    else
    {
        $sql->query(669, $params);
    }
}
#Return functions
/**
 * loggedInOrReturn()
 * 
 * @param string $url
 * @return
 */
function loggedInOrReturn($url='index.php')
{
    global $user, $Lang;
    if(!$user->logged())
    {
        if($url && $url!='')
            $_SESSION['returnto']=$url;
        header ('Refresh: 0; url=login.php');
        die;
    }
}
#Themes functions
/**
 * is_theme()
 * 
 * @param mixed $theme
 * @return
 */
function is_theme($theme) {
	return file_exists('theme/'.$theme.'/head.php') && file_exists('theme/'.$theme.'/foot.php');
}
/**
 * get_themes()
 * 
 * @return
 */
function get_themes() {
	$handle = opendir('theme');
	$themelist = array();
	while ($file = readdir($handle)) {
		if (is_theme($file) && $file != '.' && $file != '..') {
			$themelist[] = $file;
		}
	}
	closedir($handle);
	sort($themelist);
	return $themelist;
}
/**
 * theme_selector()
 * 
 * @param string $sel_theme
 * @param bool $js
 * @return
 */
function theme_selector($sel_theme = "", $js = false) {
	$themes = get_themes();
	$cnt = '<select name="theme"'.($js ? ' onchange="window.location=\'?p=chngthm&theme=\'+this.options[this.selectedIndex].value"' : '').'>';
	foreach ($themes as $theme)
    {
		$cnt .= '<option value="'.$theme.'"'.($theme == $sel_theme ? ' selected="selected"' : '').'>'.$theme.'</option>';
    }
	$cnt .= '</select>';
	return $cnt;
}
/**
 * select_theme()
 * 
 * @return
 */
function select_theme() {
    global $user;
	if ($user->logged())
		$theme = $_SESSION['theme'];
	elseif(isset($_COOKIE['theme']))
        $theme = $_COOKIE['theme'];
    else
		$theme = getConfig('settings','dtheme', 'default');
	if (!is_theme($theme))
		$theme = getConfig('settings','dtheme', 'default');
	return $theme;
}
/**
 * head()
 * 
 * @param string $title
 * @param integer $head
 * @param string $url
 * @param integer $time
 * @return
 */
function head($title='', $head=1, $url='', $time=0)
{
    global $user, $sql, $tpl, $cache, $Lang, $host, $menu;
    DEFINE('INTHEME', True);
	$theme = select_theme();
    $title = getConfig('head', 'title', 'INKO')." :: ".$title;

	require_once('theme/'.$theme.'/head.php');
}

/**
 * foot()
 * 
 * @param integer $foot
 * @return
 */
function foot($foot=1)
{
    global $user, $sql, $tpl, $cache, $Lang, $starttime;
    $theme = select_theme();
    require_once('theme/'.$theme.'/foot.php');
}
function isFloat($var)
{
    return (is_float($var) || ( (float) $var != round($var) || strlen($var) != strlen( (int) $var) ) && $var != 0 );
}
function isDate($var)
{
    if($var=='') return null;
    $delimiter=getConfig('settings','date_delimiter','.');
    //echo $var;
    $s_date = str_replace(array('\'', '-', '.', ',', ' ', '/'), $delimiter, $var);
    //echo $s_date;
    $a_date = explode($delimiter, $s_date);
    switch(getConfig('settings','date_format','d.m.Y'))
    {
        case 'd.m.Y':
            $day = $a_date[0];
            $month = $a_date[1];
            $year = $a_date[2]; 
        break;
        case 'm.d.Y':
            $day = $a_date[1];
            $month = $a_date[0];
            $year = $a_date[2]; 
        break;
        case 'Y.m.d':
            $year = $a_date[0];
            $month = $a_date[1];
            $day = $a_date[2];
        break;
    }
    if (strlen($day)==1) { $day='0'.$day; } # day -trailing zero missing
    if (strlen($month)==1) { $month='0'.$month; } # month -trailing zero missing
    if (strlen($year)==3) { $year=substr(date('Y'),0,strlen(date('Y'))-3).$year; } # year -millennium missing
    if (strlen($year)==2) { $year=substr(date('Y'),0,strlen(date('Y'))-2).$year; } # year -century missing
    if (strlen($year)==1) { $year=substr(date('Y'),0,strlen(date('Y'))-1).$year; } # year -decade missing
    switch(getConfig('settings','date_format','d.m.Y')) {
        case 'd.m.Y':
            $date = $day.$delimiter.$month.$delimiter.$year;
        break;
        case 'm.d.Y':
            $date = $month.$delimiter.$day.$delimiter.$year;
        break;
        case 'Y.m.d':
            $date = $year.$delimiter.$month.$delimiter.$day;
        break;
        default: # error message
            throw new Exception('Date isn\'t valid: '.$var);
            return NULL;
    }
    if (!is_numeric($month) || !is_numeric($day) || !is_numeric($year)) {
        return NULL;
    } elseif (!checkdate($month, $day, $year)) {
        return NULL;
    }
    return $date;
}
function SQLNull($var)
{
    return $var==null?"null":"'$var'";
}
function auto_version($file)
{
  if(!file_exists($file))
    return $file;

  $mtime = filemtime($file);
  return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}
function get_date_time($timestamp = 0) {
	if ($timestamp)
		return date("Y-m-d H:i:s", $timestamp);
	else
		return date("Y-m-d H:i:s");
}

$smilies = array(
  ":-)" => "smile1.gif",
  ":smile:" => "smile2.gif",
  ":-D" => "grin.gif",
  ":lol:" => "laugh.gif",
  ":w00t:" => "w00t.gif",
  ":-P" => "tongue.gif",
  ";-)" => "wink.gif",
  ":-|" => "noexpression.gif",
  ":-/" => "confused.gif",
  ":-(" => "sad.gif",
  ":'-(" => "cry.gif",
  ":weep:" => "weep.gif",
  ":-O" => "ohmy.gif",
  ":o)" => "clown.gif",
  "8-)" => "cool1.gif",
  "|-)" => "sleeping.gif",
  ":innocent:" => "innocent.gif",
  ":whistle:" => "whistle.gif",
  ":unsure:" => "unsure.gif",
  ":closedeyes:" => "closedeyes.gif",
  ":cool:" => "cool2.gif",
  ":fun:" => "fun.gif",
  ":thumbsup:" => "thumbsup.gif",
  ":thumbsdown:" => "thumbsdown.gif",
  ":blush:" => "blush.gif",
  ":unsure:" => "unsure.gif",
  ":yes:" => "yes.gif",
  ":no:" => "no.gif",
  ":love:" => "love.gif",
  ":?:" => "question.gif",
  ":!:" => "excl.gif",
  ":idea:" => "idea.gif",
  ":arrow:" => "arrow.gif",
  ":arrow2:" => "arrow2.gif",
  ":hmm:" => "hmm.gif",
  ":hmmm:" => "hmmm.gif",
  ":huh:" => "huh.gif",
  ":geek:" => "geek.gif",
  ":look:" => "look.gif",
  ":rolleyes:" => "rolleyes.gif",
  ":kiss:" => "kiss.gif",
  ":shifty:" => "shifty.gif",
  ":blink:" => "blink.gif",
  ":smartass:" => "smartass.gif",
  ":sick:" => "sick.gif",
  ":crazy:" => "crazy.gif",
  ":wacko:" => "wacko.gif",
  ":alien:" => "alien.gif",
  ":wizard:" => "wizard.gif",
  ":wave:" => "wave.gif",
  ":wavecry:" => "wavecry.gif",
  ":baby:" => "baby.gif",
  ":angry:" => "angry.gif",
  ":ras:" => "ras.gif",
  ":sly:" => "sly.gif",
  ":devil:" => "devil.gif",
  ":evil:" => "evil.gif",
  ":evilmad:" => "evilmad.gif",
  ":sneaky:" => "sneaky.gif",
  ":axe:" => "axe.gif",
  ":slap:" => "slap.gif",
  ":wall:" => "wall.gif",
  ":rant:" => "rant.gif",
  ":jump:" => "jump.gif",
  ":yucky:" => "yucky.gif",
  ":nugget:" => "nugget.gif",
  ":smart:" => "smart.gif",
  ":shutup:" => "shutup.gif",
  ":shutup2:" => "shutup2.gif",
  ":crockett:" => "crockett.gif",
  ":zorro:" => "zorro.gif",
  ":snap:" => "snap.gif",
  ":beer:" => "beer.gif",
  ":beer2:" => "beer2.gif",
  ":drunk:" => "drunk.gif",
  ":strongbench:" => "strongbench.gif",
  ":weakbench:" => "weakbench.gif",
  ":dumbells:" => "dumbells.gif",
  ":music:" => "music.gif",
  ":stupid:" => "stupid.gif",
  ":dots:" => "dots.gif",
  ":offtopic:" => "offtopic.gif",
  ":spam:" => "spam.gif",
  ":oops:" => "oops.gif",
  ":lttd:" => "lttd.gif",
  ":please:" => "please.gif",
  ":sorry:" => "sorry.gif",
  ":hi:" => "hi.gif",
  ":yay:" => "yay.gif",
  ":cake:" => "cake.gif",
  ":hbd:" => "hbd.gif",
  ":band:" => "band.gif",
  ":punk:" => "punk.gif",
  ":rofl:" => "rofl.gif",
  ":bounce:" => "bounce.gif",
  ":mbounce:" => "mbounce.gif",
  ":thankyou:" => "thankyou.gif",
  ":gathering:" => "gathering.gif",
  ":hang:" => "hang.gif",
  ":chop:" => "chop.gif",
  ":rip:" => "rip.gif",
  ":whip:" => "whip.gif",
  ":judge:" => "judge.gif",
  ":chair:" => "chair.gif",
  ":tease:" => "tease.gif",
  ":box:" => "box.gif",
  ":boxing:" => "boxing.gif",
  ":guns:" => "guns.gif",
  ":shoot:" => "shoot.gif",
  ":shoot2:" => "shoot2.gif",
  ":flowers:" => "flowers.gif",
  ":wub:" => "wub.gif",
  ":lovers:" => "lovers.gif",
  ":kissing:" => "kissing.gif",
  ":kissing2:" => "kissing2.gif",
  ":console:" => "console.gif",
  ":group:" => "group.gif",
  ":hump:" => "hump.gif",
  ":hooray:" => "hooray.gif",
  ":happy2:" => "happy2.gif",
  ":clap:" => "clap.gif",
  ":clap2:" => "clap2.gif",
  ":weirdo:" => "weirdo.gif",
  ":yawn:" => "yawn.gif",
  ":bow:" => "bow.gif",
  ":dawgie:" => "dawgie.gif",
  ":cylon:" => "cylon.gif",
  ":book:" => "book.gif",
  ":fish:" => "fish.gif",
  ":mama:" => "mama.gif",
  ":pepsi:" => "pepsi.gif",
  ":medieval:" => "medieval.gif",
  ":rambo:" => "rambo.gif",
  ":ninja:" => "ninja.gif",
  ":hannibal:" => "hannibal.gif",
  ":party:" => "party.gif",
  ":snorkle:" => "snorkle.gif",
  ":evo:" => "evo.gif",
  ":king:" => "king.gif",
  ":chef:" => "chef.gif",
  ":mario:" => "mario.gif",
  ":pope:" => "pope.gif",
  ":fez:" => "fez.gif",
  ":cap:" => "cap.gif",
  ":cowboy:" => "cowboy.gif",
  ":pirate:" => "pirate.gif",
  ":pirate2:" => "pirate2.gif",
  ":rock:" => "rock.gif",
  ":cigar:" => "cigar.gif",
  ":icecream:" => "icecream.gif",
  ":oldtimer:" => "oldtimer.gif",
  ":trampoline:" => "trampoline.gif",
  ":banana:" => "bananadance.gif",
  ":smurf:" => "smurf.gif",
  ":yikes:" => "yikes.gif",
  ":osama:" => "osama.gif",
  ":saddam:" => "saddam.gif",
  ":santa:" => "santa.gif",
  ":indian:" => "indian.gif",
  ":pimp:" => "pimp.gif",
  ":nuke:" => "nuke.gif",
  ":jacko:" => "jacko.gif",
  ":ike:" => "ike.gif",
  ":greedy:" => "greedy.gif",
  ":super:" => "super.gif",
  ":wolverine:" => "wolverine.gif",
  ":spidey:" => "spidey.gif",
  ":spider:" => "spider.gif",
  ":bandana:" => "bandana.gif",
  ":construction:" => "construction.gif",
  ":sheep:" => "sheep.gif",
  ":police:" => "police.gif",
  ":detective:" => "detective.gif",
  ":bike:" => "bike.gif",
  ":fishing:" => "fishing.gif",
  ":clover:" => "clover.gif",
  ":horse:" => "horse.gif",
  ":shit:" => "shit.gif",
  ":soldiers:" => "soldiers.gif",
  ":)" => "smile1.gif",
  ":wink:" => "wink.gif",
  ":D" => "grin.gif",
  ":P" => "tongue.gif",
  ":(" => "sad.gif",
  ":'(" => "cry.gif",
  ":|" => "noexpression.gif",
  ":Boozer:" => "alcoholic.gif",
  ":deadhorse:" => "deadhorse.gif",
  ":spank:" => "spank.gif",
  ":yoji:" => "yoji.gif",
  ":locked:" => "locked.gif",
  ":grrr:" => "angry.gif", 			// legacy
  "O:-" => "innocent.gif",			// legacy
  ":sleeping:" => "sleeping.gif",	// legacy
  "-_-" => "unsure.gif",			// legacy
  ":clown:" => "clown.gif",
  ":mml:" => "mml.gif",
  ":rtf:" => "rtf.gif",
  ":morepics:" => "morepics.gif",
  ":rb:" => "rb.gif",
  ":rblocked:" => "rblocked.gif",
  ":maxlocked:" => "maxlocked.gif",
  ":hslocked:" => "hslocked.gif",
);

// Set this to the line break character sequence of your system
$linebreak = "\r\n";
function htmlspecialchars_uni($message) {
		$message = preg_replace("#&(?!\#[0-9]+;)#si", "&amp;", $message); // Fix & but allow unicode
		$message = str_replace("<","&lt;",$message);
		$message = str_replace(">","&gt;",$message);
		$message = str_replace("\"","&quot;",$message);
		$message = str_replace("  ", "&nbsp;&nbsp;", $message);
		return $message;
}

function format_comment($text, $strip_html = true) {
	global $smilies;
	$smiliese = $smilies;
	$s = $text;

	$s = str_replace(";)", ":wink:", $s);


	if ($strip_html)
		$s = htmlspecialchars_uni($s);

	$bb[] = "#\[img\](?!javascript:)([^?](?:[^\[]+|\[(?!url))*?)\[/img\]#i";
	$html[] = "<img class=\"linked-image\" src=\"\\1\" border=\"0\" alt=\"\\1\" title=\"\\1\" />";
	$bb[] = "#\[img=([a-zA-Z]+)\](?!javascript:)([^?](?:[^\[]+|\[(?!url))*?)\[/img\]#is";
	$html[] = "<img class=\"linked-image\" src=\"\\2\" align=\"\\1\" border=\"0\" alt=\"\\2\" title=\"\\2\" />";
	$bb[] = "#\[img\ alt=([a-zA-Zа-яА-Я0-9\_\-\. ]+)\](?!javascript:)([^?](?:[^\[]+|\[(?!url))*?)\[/img\]#is";
	$html[] = "<img class=\"linked-image\" src=\"\\2\" align=\"\\1\" border=\"0\" alt=\"\\1\" title=\"\\1\" />";
	$bb[] = "#\[img=([a-zA-Z]+) alt=([a-zA-Zа-яА-Я0-9\_\-\. ]+)\](?!javascript:)([^?](?:[^\[]+|\[(?!url))*?)\[/img\]#is";
	$html[] = "<img class=\"linked-image\" src=\"\\3\" align=\"\\1\" border=\"0\" alt=\"\\2\" title=\"\\2\" />";
	//$bb[] = "#\[kp=([0-9]+)\]#is";
	//$html[] = "<a href=\"http://www.kinopoisk.ru/level/1/film/\\1/\" rel=\"nofollow\"><img src=\"http://www.kinopoisk.ru/rating/\\1.gif/\" alt=\"Кинопоиск\" title=\"Кинопоиск\" border=\"0\" /></a>";
	$bb[] = "#\[url\]([\w]+?://([\w\#$%&~/.\-;:=,?@\]+]+|\[(?!url=))*?)\[/url\]#is";
	$html[] = "<a href=\"\\1\" title=\"\\1\">\\1</a>";
	$bb[] = "#\[url\]((www|ftp)\.([\w\#$%&~/.\-;:=,?@\]+]+|\[(?!url=))*?)\[/url\]#is";
	$html[] = "<a href=\"http://\\1\" title=\"\\1\">\\1</a>";
	$bb[] = "#\[url=([\w]+?://[\w\#$%&~/.\-;:=,?@\[\]+]*?)\]([^?\n\r\t].*?)\[/url\]#is";
	$html[] = "<a href=\"\\1\" title=\"\\1\">\\2</a>";
	$bb[] = "#\[url=((www|ftp)\.[\w\#$%&~/.\-;:=,?@\[\]+]*?)\]([^?\n\r\t].*?)\[/url\]#is";
	$html[] = "<a href=\"http://\\1\" title=\"\\1\">\\3</a>";
	$bb[] = "/\[url=([^()<>\s]+?)\]((\s|.)+?)\[\/url\]/i";
	$html[] = "<a href=\"\\1\">\\2</a>";
	$bb[] = "/\[url\]([^()<>\s]+?)\[\/url\]/i";
	$html[] = "<a href=\"\\1\">\\1</a>";
	$bb[] = "#\[mail\](\S+?)\[/mail\]#i";
	$html[] = "<a href=\"mailto:\\1\">\\1</a>";
	$bb[] = "#\[mail\s*=\s*([\.\w\-]+\@[\.\w\-]+\.[\w\-]+)\s*\](.*?)\[\/mail\]#i";
	$html[] = "<a href=\"mailto:\\1\">\\2</a>";
	$bb[] = "#\[color=(\#[0-9A-F]{6}|[a-z]+)\](.*?)\[/color\]#si";
	$html[] = "<span style=\"color: \\1\">\\2</span>";
	$bb[] = "#\[(font|family)=([A-Za-z ]+)\](.*?)\[/\\1\]#si";
	$html[] = "<span style=\"font-family: \\2\">\\3</span>";
	$bb[] = "#\[size=([0-9]+)\](.*?)\[/size\]#si";
	$html[] = "<span style=\"font-size: \\1\">\\2</span>";
	$bb[] = "#\[(left|right|center|justify)\](.*?)\[/\\1\]#is";
	$html[] = "<div align=\"\\1\">\\2</div>";
	$bb[] = "#\[b\](.*?)\[/b\]#si";
	$html[] = "<b>\\1</b>";
	$bb[] = "#\[i\](.*?)\[/i\]#si";
	$html[] = "<i>\\1</i>";
	$bb[] = "#\[u\](.*?)\[/u\]#si";
	$html[] = "<u>\\1</u>";
	$bb[] = "#\[s\](.*?)\[/s\]#si";
	$html[] = "<s>\\1</s>";
	$bb[] = "#\[li\]#si";
	$html[] = "<li>";
	$bb[] = "#\[hr\]#si";
	$html[] = "<hr>";

	$s = preg_replace($bb, $html, $s);

	// Linebreaks
	$s = nl2br($s);

	// URLs
	//$s = format_urls($s);
	//$s = format_local_urls($s);

	// Maintain spacing
	//$s = str_replace("  ", " &nbsp;", $s);

	foreach ($smiliese as $code => $url)
		$s = str_replace($code, "<img border=\"0\" src=\"img/smilies/$url\" alt=\"" . htmlspecialchars_uni($code) . "\">", $s);

	return $s;
}
function autochat($msg = '')
{
    global $sql;
    $date=time();
    $msg=$sql->escape($msg);
    $sql->query("INSERT INTO chat (date, text, user) VALUES ('$date', '$msg', 'System');");
}
/**
 * getHost()
 * place it only in root dir
 * @return absolute web path without ending slash
 */
function getHost()
{
    if(!isset($_SERVER)) return '';
    if(!isset($_SERVER['SCRIPT_NAME'])) return '';
    $paths=explode('/',$_SERVER['SCRIPT_NAME']);
    $c=count($paths);
    $i=1;
    $dirs='';
    foreach ($paths as $path)
    {
        if($i==$c) continue;
        $i++;
        if($path=='') continue;
        $dirs.='/'.$path;
    }
    if(isset($_SERVER['SERVER_NAME']))
        return 'http://'.$_SERVER['SERVER_NAME'].$dirs;
    else
        return '';
}
function return2($url='')
{
    if($url=='')
        header ('Refresh: 0; url=index.php');
    else
        header ('Refresh: 0; url='.$url);
    die;
}
function downloadFile( $fullPath )
{
  if( headers_sent() )
    die('Headers Sent');

  // Required for some browsers
  if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

  if( file_exists($fullPath) ){
   
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
   
    switch ($ext) {
      case "pdf": $ctype="application/pdf"; break;
      case "exe": $ctype="application/octet-stream"; break;
      case "zip": $ctype="application/zip"; break;
      case "doc": $ctype="application/msword"; break;
      case "xls": $ctype="application/vnd.ms-excel"; break;
      case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
      case "gif": $ctype="image/gif"; break;
      case "png": $ctype="image/png"; break;
      case "jpeg":
      case "jpg": $ctype="image/jpg"; break;
      default: $ctype="application/force-download";
    }

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false);
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$fsize);
    ob_clean();
    flush();
    readfile( $fullPath );

  } else
    die('File Not Found');

}
function writeFile($file, $data)
{
    $handle=fopen($file,'w');
    fwrite($handle,$data);
    fclose($handle);
}
function writeXLSHead()
{
    return '<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
 <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
  <Author>PUS SYSTEM</Author>
  <LastAuthor>PUS SYSTEM</LastAuthor>
  <Created>2012-02-21T18:06:37Z</Created>
  <Company>INKO</Company>
  <Version>11.9999</Version>
 </DocumentProperties>
 <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
  <WindowHeight>9345</WindowHeight>
  <WindowWidth>11340</WindowWidth>
  <WindowTopX>480</WindowTopX>
  <WindowTopY>60</WindowTopY>
  <ProtectStructure>False</ProtectStructure>
  <ProtectWindows>False</ProtectWindows>
 </ExcelWorkbook>
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"/>
   <Borders/>
   <Font x:CharSet="186"/>
   <Interior/>
   <NumberFormat/>
   <Protection/>
  </Style>
  <Style ss:ID="s21">
   <Borders>
    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>
    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>
    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>
    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>
   </Borders>
   <Font x:CharSet="186" x:Family="Swiss" ss:Bold="1"/>
  </Style>
  <Style ss:ID="s22">
   <Borders>
    <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/>
    <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/>
    <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/>
    <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/>
   </Borders>
  </Style>
  <Style ss:ID="s23">
   <Font x:CharSet="186" x:Family="Swiss" ss:Bold="1"/>
  </Style>
 </Styles>
 <Worksheet ss:Name="Sheet1">
  <Table>';
   }
   function writeXLSFoot()
   {
    return '</Table>
  <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
   <Selected/>
   <ProtectObjects>False</ProtectObjects>
   <ProtectScenarios>False</ProtectScenarios>
  </WorksheetOptions>
 </Worksheet>
</Workbook>
';
}
function date2SQLdate($date)
{
    $n=explode('.',$date);
    return $n[2].'-'.$n[1].'-'.$n[0];
}
function checkAccess($menu,$lnk)
{
    global $user;
    foreach($menu as $m)
    {
        if($m['link']==$lnk && $user->hasAccess($m['access']))
            return true;
    }
    return false;
}
?>